<?php

namespace app\common\service;

use app\common\model\Service as ServiceModel;
use app\common\model\ServiceAttr;
use think\Db;

class Service extends Base
{

    /**
     * 过滤数据
     *
     * @param array $data 提交的原始数据
     * @return array
     */
    private function filterData($data = [])
    {
        //根据业务的类型，设置默认的值
        switch ($data['service_type']) {
                //单次服务
            case 1:
                $data['times'] = 1;
                $data['expire_type'] = 0;
                $data['expire_type_date'] = 'year';
                $data['expire_type_num'] = 1;
                break;
                //套餐服务
            case 2:
                break;
        }

        //按小时计费
        if ($data['charging_type'] == 2) {
            $data['unit'] = '小时';
        }


        return $data;
    }

    /**
     * 添加服务项目
     *
     * @param array $data 需要保存的数据
     * @return array
     */
    public function add($data)
    {

        //过滤数据
        $data = $this->filterData($data);


        //1.保存服务项目
        $service = ServiceModel::create($data);
        if (!$service) {
            return self::error('保存失败，请重试');
        }

        //多规格的相关操作
        if ($data['spec_type'] == 2) {
            //2.保存服务规格项
            if (!empty($data['rule_value'])) {
                foreach ($data['rule_value'] as $rv) {
                    $attr = [
                        'sid' => $service['id'],
                        'attr_name' => $rv['title'],
                        'attr_values' => implode(',', $rv['values']),
                        'create_time' => time()
                    ];
                    $res = Db::name('service_attr')->insert($attr);
                    if (!$res) {
                        return self::error('保存规格项失败');
                    }
                }
            }

            $min_price = 0;

            //3.保存全部sku
            if (!empty($data['rows'])) {
                $min_price = $data['rows'][0]['price'];
                foreach ($data['rows'] as $row) {
                    $item = [
                        'sid' => $service['id'],
                        'sku' => implode(',', $row['attr']),
                        'price' => $row['price'],
                        'create_time' => time()
                    ];
                    $res2 = Db::name('service_attr_value')->insert($item);
                    if (!$res2) {
                        return self::error('保存sku失败');
                    }

                    if ($row['price'] < $min_price) {
                        $min_price = $row['price'];
                    }
                }
            }

            //4.更新服务项目的最低价
            $service->price = $min_price;
            $res3 = $service->save();
            if (false === $res3) {
                return self::error('更新服务项目信息失败');
            }
        }


        return self::success($service->toArray());
    }

    /**
     * 修改服务项目
     *
     * @param array $data
     * @return array
     */
    public function edit($data)
    {
        //过滤数据
        $data = $this->filterData($data);
        $service = ServiceModel::get($data['id']);
        if (empty($service)) {
            return self::error('服务不存在');
        }

        //多规格的相关操作
        if ($data['spec_type'] == 2) {
            $spec_unique = md5(json_encode($data['rows'], JSON_UNESCAPED_UNICODE));
            if ($spec_unique != $service['spec_unique']) {
                //多规格已变更，则需要删除已有的规格属性，重新生成新的规格属性
                $data['spec_unique'] = $spec_unique;
                //清空原来的规格项目
                $res = Db::name('service_attr')->where('sid', $data['id'])->delete();
                if (false === $res) {
                    return self::error('操作失败');
                }
                $res2 = Db::name('service_attr_value')->where('sid', $data['id'])->delete();
                if (false === $res2) {
                    return self::error('操作失败');
                }

                //2.保存服务规格项
                if (!empty($data['rule_value'])) {
                    foreach ($data['rule_value'] as $rv) {
                        $attr = [
                            'sid' => $service['id'],
                            'attr_name' => $rv['title'],
                            'attr_values' => implode(',', $rv['values']),
                            'create_time' => time()
                        ];
                        $res = Db::name('service_attr')->insert($attr);
                        if (!$res) {
                            return self::error('保存规格项失败');
                        }
                    }
                }

                $min_price = 0;

                //3.保存全部sku
                if (!empty($data['rows'])) {
                    $min_price = $data['rows'][0]['price'];
                    foreach ($data['rows'] as $row) {
                        $item = [
                            'sid' => $service['id'],
                            'sku' => implode(',', $row['attr']),
                            'price' => $row['price'],
                            'create_time' => time()
                        ];
                        $res2 = Db::name('service_attr_value')->insert($item);
                        if (!$res2) {
                            return self::error('保存sku失败');
                        }

                        if ($row['price'] < $min_price) {
                            $min_price = $row['price'];
                        }
                    }
                }

                //4.更新服务项目的最低价
                $data['price'] = $min_price;
            }
        }


        //保存最新的服务项目数据
        $res = $service->save($data);
        if (!$res) {
            return self::error('保存失败，请重试');
        }

        return self::success();
    }

    /**
     * 获取服务的详细信息
     *
     * @param int $service_id
     * @return array
     */
    public function getServiceDetail($service_id)
    {
        $service = ServiceModel::get($service_id);
        if (!$service) {
            return self::error('服务项目不存在');
        }



        //查询该服务下单规格项
        if ($service['spec_type'] == 2) {

            $attrs = ServiceAttr::where('sid', $service_id)->order('id asc')->select();
            $service['attrs'] = $attrs ? $attrs->toArray() : [];
            $service['attr_values'] = Db::name('service_attr_value')->where('sid', $service_id)->order('id asc')->select();
        }

        return self::success($service->toArray());
    }
}
